package com.zx.security.block.config;

import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.security.oauth2.jwt.JwtDecoder;
import org.springframework.security.oauth2.jwt.NimbusJwtDecoder;
import org.springframework.web.client.RestTemplate;

/**
 * <p>
 * description: 单独配置解决循环依赖  <br>
 * create: 2025-05-06 11:23
 * </p>
 *
 * @author zhou  xun
 */
@Configuration
@RefreshScope
@RequiredArgsConstructor
public class JwtConfiguration {
    private final RestTemplate restTemplate;

    /**
     * jwt解码器
     *
     * @param jwkSetUri 授权服务器JWK Set 端点
     * @return {@link JwtDecoder}
     * @author zhou  xun
     * @since 2025-05-11
     */
    @Bean
    @Primary
    @ConditionalOnProperty(
            prefix = "spring.security.oauth2.resourceserver.jwt",
            name = "jwk-set-uri"
    )
    public JwtDecoder jwtDecoder(@Value("${spring.security.oauth2.resourceserver.jwt.jwk-set-uri}")
                                 String jwkSetUri) {
        return NimbusJwtDecoder.withJwkSetUri(jwkSetUri)
                .restOperations(restTemplate).build();
    }
}